#include "APIRequestHandler.h"
#include <spdlog/spdlog.h>
#include <sstream>
#include <cstring>

namespace MessageFramework {

// ==================== APIRequestBody实现 ====================

APIRequestBody APIRequestBody::fromJson(const std::string& json) {
    APIRequestBody request;
    std::memset(&request, 0, sizeof(request));

    // 简化的JSON解析
    auto extractString = [&](const std::string& key) -> std::string {
        std::string pattern = "\"" + key + "\":\"";
        size_t start = json.find(pattern);
        if (start == std::string::npos) return "";
        start += pattern.length();
        size_t end = json.find("\"", start);
        if (end == std::string::npos) return "";
        return json.substr(start, end - start);
    };

    std::strncpy(request.requestType, extractString("requestType").c_str(),
                 sizeof(request.requestType) - 1);
    std::strncpy(request.userId, extractString("userId").c_str(),
                 sizeof(request.userId) - 1);
    std::strncpy(request.params, extractString("params").c_str(),
                 sizeof(request.params) - 1);

    return request;
}

std::string APIRequestBody::toJson() const {
    std::ostringstream oss;
    oss << "{"
        << "\"requestType\":\"" << requestType << "\","
        << "\"userId\":\"" << userId << "\","
        << "\"params\":\"" << params << "\""
        << "}";
    return oss.str();
}

APIRequestType APIRequestBody::getRequestType() const {
    if (std::strcmp(requestType, "QUERY_ACCOUNT") == 0) {
        return APIRequestType::QUERY_ACCOUNT;
    } else if (std::strcmp(requestType, "QUERY_POSITION") == 0) {
        return APIRequestType::QUERY_POSITION;
    } else if (std::strcmp(requestType, "QUERY_ORDER") == 0) {
        return APIRequestType::QUERY_ORDER;
    } else if (std::strcmp(requestType, "PLACE_ORDER") == 0) {
        return APIRequestType::PLACE_ORDER;
    } else if (std::strcmp(requestType, "CANCEL_ORDER") == 0) {
        return APIRequestType::CANCEL_ORDER;
    } else {
        return APIRequestType::UNKNOWN;
    }
}

// ==================== APIResponseBody实现 ====================

APIResponseBody APIResponseBody::fromJson(const std::string& json) {
    APIResponseBody response;
    std::memset(&response, 0, sizeof(response));

    // 简化的JSON解析
    auto extractString = [&](const std::string& key) -> std::string {
        std::string pattern = "\"" + key + "\":\"";
        size_t start = json.find(pattern);
        if (start == std::string::npos) return "";
        start += pattern.length();
        size_t end = json.find("\"", start);
        if (end == std::string::npos) return "";
        return json.substr(start, end - start);
    };

    auto extractInt = [&](const std::string& key) -> int {
        std::string pattern = "\"" + key + "\":";
        size_t start = json.find(pattern);
        if (start == std::string::npos) return 0;
        start += pattern.length();
        size_t end = json.find_first_of(",}", start);
        if (end == std::string::npos) return 0;
        return std::stoi(json.substr(start, end - start));
    };

    response.code = extractInt("code");
    std::strncpy(response.message, extractString("message").c_str(),
                 sizeof(response.message) - 1);
    std::strncpy(response.data, extractString("data").c_str(),
                 sizeof(response.data) - 1);

    return response;
}

std::string APIResponseBody::toJson() const {
    std::ostringstream oss;
    oss << "{"
        << "\"code\":" << code << ","
        << "\"message\":\"" << message << "\","
        << "\"data\":\"" << data << "\""
        << "}";
    return oss.str();
}

// ==================== APIRequestHandler实现 ====================

APIRequestHandler::APIRequestHandler(MessageProducerPtr producer, RequestCallback callback)
    : m_producer(producer), m_callback(callback) {
}

void APIRequestHandler::setCallback(RequestCallback callback) {
    m_callback = callback;
}

void APIRequestHandler::setProducer(MessageProducerPtr producer) {
    m_producer = producer;
}

APIResponseBody APIRequestHandler::createErrorResponse(int code, const std::string& message) {
    APIResponseBody response;
    std::memset(&response, 0, sizeof(response));
    response.code = code;
    std::strncpy(response.message, message.c_str(), sizeof(response.message) - 1);
    return response;
}

bool APIRequestHandler::sendResponse(const MessageHeader& requestHeader,
                                     const APIResponseBody& response) {
    if (!m_producer) {
        spdlog::error("MessageProducer not set, cannot send response");
        return false;
    }

    // 检查是否有replyStream
    if (std::strlen(requestHeader.replyStream) == 0) {
        spdlog::warn("No replyStream specified in request, response not sent");
        return false;
    }

    // 构建响应消息
    MessageHeader responseHeader;
    std::snprintf(responseHeader.targetStream, sizeof(responseHeader.targetStream),
                  "%s", requestHeader.replyStream);

    std::snprintf(responseHeader.messageType, sizeof(responseHeader.messageType),
                  "%s", "APIResponse");

    std::snprintf(responseHeader.consumerId, sizeof(responseHeader.consumerId),
                  "%s", requestHeader.publisherId);  // 响应发给请求者

    // 设置追踪信息（保持调用链）
    std::snprintf(responseHeader.traceId, sizeof(responseHeader.traceId),
                  "%s", requestHeader.traceId);

    std::snprintf(responseHeader.parentId, sizeof(responseHeader.parentId),
                  "%s", requestHeader.messageId);

    // 发送响应
    std::string streamId = m_producer->send(responseHeader, response.toJson());

    if (streamId.empty()) {
        spdlog::error("Failed to send API response");
        return false;
    }

    spdlog::debug("API response sent to stream: {}, messageId: {}",
                 requestHeader.replyStream, streamId);
    return true;
}

int APIRequestHandler::handleMessage(const Message& message) {
    spdlog::info("APIRequestHandler processing message: {}", message.header.messageId);

    // 1. 解析请求体
    APIRequestBody request;
    try {
        request = APIRequestBody::fromJson(message.body);
    } catch (const std::exception& e) {
        spdlog::error("Failed to parse API request: {}", e.what());

        auto errorResponse = createErrorResponse(-1, "Invalid request format");
        sendResponse(message.header, errorResponse);
        return -1;
    }

    // 2. 验证请求
    if (std::strlen(request.requestType) == 0) {
        spdlog::error("Invalid request: requestType is empty");

        auto errorResponse = createErrorResponse(-2, "Request type is empty");
        sendResponse(message.header, errorResponse);
        return -2;
    }

    if (std::strlen(request.userId) == 0) {
        spdlog::error("Invalid request: userId is empty");

        auto errorResponse = createErrorResponse(-3, "User ID is empty");
        sendResponse(message.header, errorResponse);
        return -3;
    }

    // 3. 调用回调处理请求
    APIResponseBody response;

    if (m_callback) {
        try {
            response = m_callback(request, message.header);

            spdlog::info("API request processed: type={}, userId={}, code={}",
                       request.requestType, request.userId, response.code);

        } catch (const std::exception& e) {
            spdlog::error("Exception in API request callback: {}", e.what());
            response = createErrorResponse(-4, "Internal server error");
        }
    } else {
        spdlog::warn("No callback registered for APIRequestHandler");
        response = createErrorResponse(-5, "Handler not configured");
    }

    // 4. 发送响应
    if (!sendResponse(message.header, response)) {
        spdlog::error("Failed to send API response");
        return -6;
    }

    return 0;
}

} // namespace MessageFramework
